﻿using Library.Core.Domain;
using Library.Core.Domain.Specification;
using Synthesize.BaseSet.Domain.Aggregation.Entity.Authority;
using Synthesize.BaseSet.Domain.Repository.Authority;
using System.Threading.Tasks;

namespace Synthesize.BaseSet.Domain.Specifications.Authority.Department
{
    public class DeleteDepartmentSpecification : IOperateSpecification<DepartmentInfoEntity>
    {
        private readonly IDepartmentRepository _departmentRepository;
        private readonly IUserDepartmentRepository _userDepartmentRepository;

        public DeleteDepartmentSpecification(IDepartmentRepository departmentRepository
            , IUserDepartmentRepository userDepartmentRepository)
        {
            _departmentRepository = departmentRepository;
            _userDepartmentRepository = userDepartmentRepository;
        }

        public async Task<bool> SatisfiedBy(DepartmentInfoEntity entity)
        {
            if (await _userDepartmentRepository.AnyAsync(x => x.DepartmentId == entity.Id))
            {
                throw new DomainException("该部门存在用户，不能删除");
            }
            if (await _departmentRepository.AnyAsync(x => x.ParentId.Equals(entity.Id)))
            {
                throw new DomainException("该部门存在下级部门，不能删除");
            }
            return true;
        }
    }
}
